<?php

namespace App\Http\Controllers\Api\V1;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
use App\Services\ApplyGoldCoinWithdraw\ApplyGoldCoinWithdraw;
use App\Services\ApplyGoldCoinWithdraw\ApplyGoldCoinWithdrawRequest;

class WithdrawsController extends Controller
{
	public function withdrawStore()
    {
    	$lock = Cache::lock('withdraw', 30);

    	try {

    		if (! $lock->get()) fail('太快了，请再试一次');

    		$request = app(ApplyGoldCoinWithdrawRequest::class);

    		$user = $request->user();

    		$withdraw = $user->withdraws()->whereDate("created_at",Carbon::today())->where('method','alipay')->where('status',"!=",'failed')->orderByDesc('id')->first();
		    
		    if($withdraw){
		    	fail('今日已申请提现，不可重复申请');
		    }

		    app(ApplyGoldCoinWithdraw::class, [
			    'user' => $user,
			    'coins' => $request->money
		    ])->apply();

		   // $user->resetPayCodeTry();

	    } finally {
    		$lock->release();
	    }

	    return response(null, 204);
    }

    public function config()
    {
	    /**
	     * @var User $user
	     */
	    $config=[
	    	'alipay_withdraw_percent' => cs("withdraw")->charge_percent,
	    	'bank_withdraw_percent'=>cs("withdraw")->xzb_charge_percent,
	    	'is_alipay_withdraw_open'=>cs("withdraw")->is_alipay_withdraw_open,
	    	'is_bank_withdraw_open'=>cs("withdraw")->is_bank_withdraw_open,
	    	'description' =>cs("withdraw")->description, 
	    	'withdraw_time'=>cs("withdraw")->withdraw_start_time.'-'.cs("withdraw")->withdraw_end_time,
	    ]; 
	     return response()->json($config);
    }
}
